package com.ruicar.afs.cloud.afscase.channel.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruicar.afs.cloud.afscase.channel.common.Constants;
import com.ruicar.afs.cloud.afscase.channel.condition.CarDealerCondition;
import com.ruicar.afs.cloud.afscase.channel.entity.*;
import com.ruicar.afs.cloud.afscase.channel.enums.FeeTypeEnum;
import com.ruicar.afs.cloud.afscase.channel.service.*;
import com.ruicar.afs.cloud.afscase.channel.vo.ChannelCaseInfoVo;
import com.ruicar.afs.cloud.afscase.loandealerfirstmortgage.entity.LoanDealerFirstMortgage;
import com.ruicar.afs.cloud.afscase.loandealerfirstmortgage.service.LoanDealerFirstMortgageService;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.common.modules.enums.BusinessType;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.math.BigDecimal;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName ChannelOnlineInfoServiceImpl
 * @Description: mq接收渠道信息service
 * @Author mingzhi.li
 * @Date 2020/9/24
 * @Version V1.0
 **/
@Slf4j
@Service
@Component
@AllArgsConstructor
public class ChannelOnlineInfoServiceImpl implements ChannelOnlineInfoService {
    /**
     * 同步渠道信息保存
     */
    private ChannelBaseInfoService channelBusiInfoService;

    /**
     * 同步风控信息
     */
    private ChannelRiskInfoService channelRiskInfoService;

    /**
     * 同步收款账号信息
     */
    private ChannelAccountInfoService channelAccountInfoService;

    /**
     * 同步保证金信息
     */
    private ChannelQuotaInfoService channelQuotaInfoService;

    /**
     * 同步授权区域信息
     */
    private ChannelAuthorizeRegionService channelAuthorizeRegionService;

    /**
     * 同步授权车型信息
     */
    private ChannelAuthorizeVehicleService channelAuthorizeVehicleService;
    /**
     * 凭证
     */
    private final ChannelVoucherInfoService channelVoucherInfoService;
    private LoanDealerFirstMortgageService loanDealerFirstMortgageService;

    @Override
    public boolean saveOrUpdateChannelInfo(ChannelCaseInfoVo vo) {

        if (vo.getChannelBaseInfo().getId() == null) {
            log.info("渠道id不能为空！！！");
            return false;
        }
        //业务类型：新车二手车
        String businessType = vo.getBusinessType();
        //基本信息同步
        ChannelBaseInfo channelBaseInfo = vo.getChannelBaseInfo();
        if (channelBaseInfo != null) {
            ChannelBaseInfo baseInfo = channelBusiInfoService.getOne(Wrappers.<ChannelBaseInfo>query().lambda().eq(ChannelBaseInfo::getId, channelBaseInfo.getId()));
            //保存前先删除数据
            if (baseInfo != null) {
                channelBusiInfoService.updateById(channelBaseInfo);
            } else {
                channelBaseInfo.setChannelId(channelBaseInfo.getId());
                channelBaseInfo.setId(channelBaseInfo.getId());
                channelBusiInfoService.save(channelBaseInfo);
            }

            //渠道风控信息同步
            List<ChannelRiskInfo> channelRiskInfoList = vo.getRisk();
            List<ChannelRiskInfo> channelRiskInfoTempList = channelRiskInfoService.list(Wrappers.<ChannelRiskInfo>query().lambda()
                    .eq(ChannelRiskInfo::getChannelId, channelBaseInfo.getId())
                    .eq(ChannelRiskInfo::getBusinessType, businessType));
            //同步信息前删除数据
            if (channelRiskInfoTempList != null && channelRiskInfoTempList.size() > 0) {
                for (ChannelRiskInfo risk : channelRiskInfoTempList) {
                    channelRiskInfoService.removeById(risk.getId());
                }
            }
            if (channelRiskInfoList != null && channelRiskInfoList.size() > 0) {
                channelRiskInfoService.saveBatch(channelRiskInfoList);
            }

            //渠道同步收款账号表
            List<ChannelReceivablesAccount> channelReceivablesAccountList = vo.getAcount();
            List<ChannelReceivablesAccount> accountList = channelAccountInfoService.list(Wrappers.<ChannelReceivablesAccount>query().lambda()
                    .eq(ChannelReceivablesAccount::getChannelId, channelBaseInfo.getId().toString())
                    .eq(ChannelReceivablesAccount::getAccountAttribute, businessType));
            if (channelReceivablesAccountList != null && channelReceivablesAccountList.size() > 0) {
                if (accountList != null && accountList.size() > 0) {
                    //同步信息前删除数据
                    for (ChannelReceivablesAccount account : accountList) {
                        channelAccountInfoService.removeById(account.getId());
                    }
                }
                if (channelReceivablesAccountList != null && channelReceivablesAccountList.size() > 0) {
                    channelAccountInfoService.saveBatch(channelReceivablesAccountList);
                }
            }

            //渠道同步额度信息表
            List<ChannelQuotaInfo> channelQuotaInfoList = vo.getQuota();
            List<ChannelQuotaInfo> quotaInfoList = channelQuotaInfoService.list(Wrappers.<ChannelQuotaInfo>query().lambda()
                    .eq(ChannelQuotaInfo::getChannelId, channelBaseInfo.getId())
                    .eq(ChannelQuotaInfo::getBusinessType, businessType));
            if (quotaInfoList != null && quotaInfoList.size() > 0) {
                //同步信息前删除数据
                for (ChannelQuotaInfo quotaInfo : quotaInfoList) {
                    channelQuotaInfoService.removeById(quotaInfo.getId());
                }
            }
            if (channelQuotaInfoList != null && channelQuotaInfoList.size() > 0) {
                channelQuotaInfoService.saveBatch(channelQuotaInfoList);
            }

            //渠道同步授权区域信息表
            List<ChannelAuthorizeRegion> channelAuthorizeRegionList = vo.getRegion();
            channelAuthorizeRegionService.remove(Wrappers.<ChannelAuthorizeRegion>query().lambda()
                    .eq(ChannelAuthorizeRegion::getChannelId, channelBaseInfo.getId())
                    .eq(ChannelAuthorizeRegion::getBusinessType, businessType));
            if (channelAuthorizeRegionList != null && channelAuthorizeRegionList.size() > 0) {
                int size = channelAuthorizeRegionList.size();
                if (size <= 1000) {
                    channelAuthorizeRegionService.saveOrUpdateBatch(channelAuthorizeRegionList);
                } else {
                    for (int i = 0; i < size / 1000; i++) {
                        if (size / 1000 - i > 1) {
                            channelAuthorizeRegionService.saveOrUpdateBatch(channelAuthorizeRegionList.subList(1000 * i, 1000 * i + 999));
                        } else {
                            channelAuthorizeRegionService.saveOrUpdateBatch(channelAuthorizeRegionList.subList(1000 * i, size - 1));
                        }
                    }
                }
            }

            //渠道同步授权区域展业信息表
            if (channelAuthorizeRegionList != null && channelAuthorizeRegionList.size() > 0) {
                for(int i=0;i<channelAuthorizeRegionList.size();i++){
                    LoanDealerFirstMortgage loanDealerFirstMortgage = new LoanDealerFirstMortgage();
                    loanDealerFirstMortgage.setChannelType(channelAuthorizeRegionList.get(i).getBusinessType());
                    loanDealerFirstMortgage.setCityCode(channelAuthorizeRegionList.get(i).getCode());
                    loanDealerFirstMortgage.setCityName(channelAuthorizeRegionList.get(i).getTitle());
                    loanDealerFirstMortgage.setDealerNo(channelAuthorizeRegionList.get(i).getChannelId().toString());
                    loanDealerFirstMortgage.setDealerName(channelBaseInfo.getChannelFullName());
                    loanDealerFirstMortgageService.saveOrUpdate(loanDealerFirstMortgage);
                }
            }
            //渠道同步授权车型
            List<ChannelAuthorizeVehicle> authorizeVehicleList = vo.getVehicle();
            channelAuthorizeVehicleService.remove(Wrappers.<ChannelAuthorizeVehicle>query().lambda()
                    .eq(ChannelAuthorizeVehicle::getChannelId, channelBaseInfo.getId())
                    .eq(ChannelAuthorizeVehicle::getBusinessType, businessType));
            if (authorizeVehicleList != null && authorizeVehicleList.size() > 0) {
                int size = authorizeVehicleList.size();
                if (size <= 1000) {
                    channelAuthorizeVehicleService.saveBatch(authorizeVehicleList);
                } else {
                    for (int i = 0; i < size / 1000; i++) {
                        if (size / 1000 - i > 1) {
                            channelAuthorizeVehicleService.saveBatch(authorizeVehicleList.subList(1000 * i, 1000 * i + 999));
                        } else {
                            channelAuthorizeVehicleService.saveBatch(authorizeVehicleList.subList(1000 * i, size - 1));
                        }
                    }
                }
            }
            //测试凭证 异常暂时捕捉
            try {
                //判断是否保证金且保证金金额不为零
                if (vo.getRisk() != null && vo.getRisk().size() > 0 && vo.getRisk().get(0).getChannelDepositPaidIn() != null && vo.getRisk().get(0).getChannelDepositPaidIn().compareTo(BigDecimal.ZERO) != 0) {
                    //凭证信息保存并推送数据
                    List<ChannelVoucherInfo> list = new ArrayList<>();
                    //保证金实收
                    BigDecimal channelDepositPaidIn = vo.getRisk().get(0).getChannelDepositPaidIn();
                    ChannelVoucherInfo info = new ChannelVoucherInfo();
                    info.setChannelId(channelBaseInfo.getChannelId());
                    info.setFeeType(FeeTypeEnum.BOND);
                    info.setAmount(channelDepositPaidIn);
                    info.setEventId(channelBaseInfo.getEventId());
                    // 业务类型
                    if (Constants.BUSINESS_TYPE_NEW_CAR.equals(businessType)) { //新车
                        info.setBusinessType(BusinessType.NEW_CAR);
                    } else if (Constants.BUSINESS_TYPE_OLD_CAR.equals(businessType)) {//新车
                        info.setBusinessType(BusinessType.OLD_CAR);
                    } else {
                        Assert.isTrue(false, MessageFormat.format("业务类型:{0},暂不支持！", businessType));
                    }
                    list.add(info);
                    channelVoucherInfoService.saveVoucher(list, channelBaseInfo.getChannelFullName());
                }
            } catch (Exception e) {
                log.error("凭证流水保存失败");
            }
        }
        return true;
    }
}
